﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using ContactSMS.Client.Models;
using ContactSMS.Client.Service;
using ContactSMS.Client.Views;
using Microsoft.Maui.Controls;
using System.Collections.ObjectModel;

namespace ContactSMS.Client.ViewModels
{
    public partial class CallRecordsViewModel : ObservableObject
    {
        [ObservableProperty]
        private string selectedButton;

        [ObservableProperty]
        private string selectedBoxViewIsVisible;

        [ObservableProperty]
        public ObservableCollection<CallRecordsModel> callRecords = new ObservableCollection<CallRecordsModel>();

        [ObservableProperty]
        public ObservableCollection<CallLogModelNew> callRecordList = new ObservableCollection<CallLogModelNew>();

        private readonly PhoneRecordService phoneRecordService;

        public CallRecordsViewModel(PhoneRecordService phoneRecordService)
        {
            SelectedButton = "1";
            SelectedBoxViewIsVisible = "1";
            this.LoadCallRecords();
            this.phoneRecordService = phoneRecordService;
        }

        public async Task LoadCallLogs(int page = 1, int pageSize = 15)
        {
            try
            {
                var result = await phoneRecordService.GetPhoneRecordsAsync(0, page, pageSize);
                if (result != null && result.Success)
                {
                    CallRecordList = new ObservableCollection<CallLogModelNew>(result.Data.List);
                }
                else
                {
                    await Application.Current.MainPage.DisplayAlert("Error", result?.Message ?? "Failed to load contacts", "OK");
                }
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "OK");
            }
        }

        private void LoadCallRecords()
        {
            for (int i = 0; i < 15; i++)
            {
                long id = i + 1;
                var record = new CallRecordsModel()
                {
                    Id = id,
                    Name = "联系人" + id,
                    Date = "18/8",
                    Address = "湖北恩施 联通"
                };
                CallRecords.Add(record);
            }
        }

        [RelayCommand]
        public void ConditionalFilter(object obj)
        {
            string key = obj.ToString();
            SelectedButton = key;
            SelectedBoxViewIsVisible = key;
        }

        [RelayCommand]
        public async Task NavigateToDetail()
        {
            await Shell.Current.GoToAsync(nameof(ContactDetailPage));
        }
    }
}
